import pygame
import sys
import math

# 定义常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TOTAL_WIDTH = SCREEN_WIDTH

# 定义颜色 - 使用贪吃蛇的绿色主题
BG_COLOR = (10, 40, 10)  # 深绿色背景，类似森林主题
TEXT_COLOR = (255, 255, 255)
MENU_BG_COLOR = (20, 50, 20)  # 菜单背景色
MENU_HIGHLIGHT_COLOR = (255, 215, 0)  # 金色强调色
MENU_NORMAL_COLOR = (128, 128, 128)
BUTTON_BG_COLOR = (30, 70, 30)
BUTTON_HOVER_COLOR = (50, 90, 50)
BUTTON_BORDER_COLOR = (100, 150, 100)
NEON_GREEN = (0, 255, 100)  # 霓虹绿色，类似贪吃蛇的蛇头色
WHITE = (255, 255, 255)

# 全局变量
menu_buttons = []  # 存储菜单按钮

def draw_gradient_rect(surface, color1, color2, rect, vertical=True):
    """绘制渐变矩形"""
    if vertical:
        for y in range(rect.height):
            blend = y / rect.height
            r = int(color1[0] * (1 - blend) + color2[0] * blend)
            g = int(color1[1] * (1 - blend) + color2[1] * blend)
            b = int(color1[2] * (1 - blend) + color2[2] * blend)
            pygame.draw.line(surface, (r, g, b),
                             (rect.x, rect.y + y), (rect.x + rect.width, rect.y + y))
    else:
        for x in range(rect.width):
            blend = x / rect.width
            r = int(color1[0] * (1 - blend) + color2[0] * blend)
            g = int(color1[1] * (1 - blend) + color2[1] * blend)
            b = int(color1[2] * (1 - blend) + color2[2] * blend)
            pygame.draw.line(surface, (r, g, b),
                             (rect.x + x, rect.y), (rect.x + x, rect.y + rect.height))

def draw_rounded_rect(surface, color, rect, radius=12, width=0):
    """绘制圆角矩形"""
    pygame.draw.rect(surface, color, rect, width=width, border_radius=radius)

def draw_glowing_rect(surface, color, rect, glow_size=2):
    """绘制发光效果的矩形"""
    # 绘制外层发光
    for i in range(glow_size, 0, -1):
        glow_color = tuple(min(255, c + 20 * i) for c in color)
        glow_rect = pygame.Rect(rect.x - i, rect.y - i, rect.width + 2 * i, rect.height + 2 * i)
        pygame.draw.rect(surface, glow_color, glow_rect, border_radius=8)

    # 绘制主体
    pygame.draw.rect(surface, color, rect, border_radius=6)

def draw_snake_logo(screen, x, y, size=40):
    """绘制贪吃蛇风格的Logo - 一条经典的贪吃蛇"""
    block_size = size // 6
    colors = [
        (255, 255, 0),  # 蛇头 - 黄色
        (0, 255, 100),  # 蛇身 - 绿色
        (0, 200, 80),   # 蛇身 - 深绿色
        (0, 150, 60),   # 蛇身 - 更深的绿色
        (0, 100, 40),   # 蛇尾 - 最深的绿色
    ]
    
    # 绘制一条完整的S形状蛇，添加连接方块
    positions = [
        # 蛇头 (右侧)
        (5, 1),  # 蛇头
        
        # 蛇身第一行 (从左到右)
        (4, 1),  # 蛇身第一段
        (3, 1),  # 蛇身第二段
        (2, 1),  # 蛇身第三段
        (1, 1),  # 蛇身第四段
        (0, 1),  # 蛇身第五段
        
        # 连接方块 (从第一行到第二行)
        (0, 2),  # 连接方块1
        
        # 蛇身第二行 (从右到左)
        (0, 3),  # 蛇身第六段
        (1, 3),  # 蛇身第七段
        (2, 3),  # 蛇身第八段
        (3, 3),  # 蛇身第九段
        (4, 3),  # 蛇身第十段
        (5, 3),  # 蛇身第十一段
        
        # 连接方块 (从第二行到第三行)
        (5, 4),  # 连接方块2
        
        # 蛇身第三行 (从左到右)
        (5, 5),  # 蛇身第十二段
        (4, 5),  # 蛇身第十三段
        (3, 5),  # 蛇身第十四段
        (2, 5),  # 蛇身第十五段
        (1, 5),  # 蛇身第十六段
        (0, 5),  # 蛇尾
    ]
    
    # 绘制蛇身，使用渐变颜色
    for i, (dx, dy) in enumerate(positions):
        # 根据位置计算颜色渐变
        if i == 0:  # 蛇头
            color = colors[0]
        elif i < 5:  # 蛇身前段
            color = colors[1]
        elif i < 10:  # 蛇身中段
            color = colors[2]
        elif i < 15:  # 蛇身后段
            color = colors[3]
        else:  # 蛇尾
            color = colors[4]
        
        rect = pygame.Rect(x + dx * block_size, y + dy * block_size, block_size, block_size)
        draw_glowing_rect(screen, color, rect, glow_size=1)
    
    # 绘制蛇的眼睛（在与蛇舌连接的方块上，顶部和底部各一个小黑点）
    eye_radius = block_size // 6
    # 眼睛位置在蛇头方块上，顶部和底部各一个小黑点
    eye1 = (x + 5 * block_size + block_size // 2, y + block_size + block_size // 4)  # 顶部眼睛
    eye2 = (x + 5 * block_size + block_size // 2, y + block_size + 3 * block_size // 4)  # 底部眼睛
    pygame.draw.circle(screen, (0, 0, 0), eye1, eye_radius)
    pygame.draw.circle(screen, (0, 0, 0), eye2, eye_radius)
    
    # 添加蛇头的舌头效果（从蛇头方块中心伸出）
    tongue_color = (255, 100, 100)
    tongue_points = [
        (x + 6 * block_size, y + block_size + block_size // 2),  # 舌头根部（从蛇头方块中心）
        (x + 6.5 * block_size, y + block_size + block_size // 2 - 2),  # 舌头分叉上
        (x + 7 * block_size, y + block_size + block_size // 2),  # 舌头尖端
        (x + 6.5 * block_size, y + block_size + block_size // 2 + 2),  # 舌头分叉下
    ]
    pygame.draw.polygon(screen, tongue_color, tongue_points)

def draw_menu(screen, total_width, screen_height):
    """绘制主菜单界面 - 供主游戏调用"""
    # 在函数内部加载字体，避免在模块导入时就初始化
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 48, bold=True)
    subtitle_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)
    
    # 创建按钮列表
    menu_buttons = []
    
    # 绘制背景渐变
    draw_gradient_rect(screen, BG_COLOR, (0, 20, 0), 
                       pygame.Rect(0, 0, total_width, screen_height))
    
    # 绘制装饰性网格（贪吃蛇风格）
    for x in range(0, total_width, 40):
        pygame.draw.line(screen, (20, 60, 20), (x, 0), (x, screen_height), 1)
    for y in range(0, screen_height, 40):
        pygame.draw.line(screen, (20, 60, 20), (0, y), (total_width, y), 1)
    
    # 计算布局参数
    logo_size = 120
    logo_y = 20  # 将Logo位置进一步上移，与文字保持更远距离
    logo_x = total_width // 2 - logo_size // 2
    
    # 绘制Logo
    draw_snake_logo(screen, logo_x, logo_y, logo_size)
    
    # 绘制标题（在Logo下方，增加距离）
    title_text = title_font.render("贪吃蛇", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(total_width // 2, logo_y + logo_size + 50))
    
    # 绘制发光效果
    for i in range(3):
        glow_color = tuple(min(255, c + 30 - i * 10) for c in MENU_HIGHLIGHT_COLOR)
        glow_text = title_font.render("贪吃蛇", True, glow_color)
        screen.blit(glow_text, (title_rect.x - i, title_rect.y - i))
    
    screen.blit(title_text, title_rect)
    
    # 绘制副标题（在标题下方，增加间距）
    subtitle_text = subtitle_font.render("经典休闲游戏", True, NEON_GREEN)
    subtitle_rect = subtitle_text.get_rect(center=(total_width // 2, title_rect.bottom + 30))
    screen.blit(subtitle_text, subtitle_rect)
    
    # 创建按钮（在副标题下方，合理分布）
    button_width = 220
    button_height = 55
    button_spacing = 25  # 增加按钮间距
    total_buttons_height = 3 * button_height + 2 * button_spacing
    buttons_start_y = subtitle_rect.bottom + 60  # 减少与副标题的距离，整体上移
    
    button_x = total_width // 2 - button_width // 2
    
    # 开始游戏按钮
    start_button = pygame.Rect(button_x, buttons_start_y, button_width, button_height)
    menu_buttons.append(("start", start_button))
    
    # 游戏规则按钮
    rules_button = pygame.Rect(button_x, buttons_start_y + button_height + button_spacing, button_width, button_height)
    menu_buttons.append(("rules", rules_button))
    
    # 退出游戏按钮
    exit_button = pygame.Rect(button_x, buttons_start_y + 2 * (button_height + button_spacing), button_width, button_height)
    menu_buttons.append(("exit", exit_button))
    
    # 绘制按钮
    for action, button_rect in menu_buttons:
        # 根据悬停状态选择颜色
        is_hover = button_rect.collidepoint(pygame.mouse.get_pos())
        
        if is_hover:
            # 悬停状态：发光效果
            draw_glowing_rect(screen, BUTTON_HOVER_COLOR, button_rect, glow_size=3)
            text_color = MENU_HIGHLIGHT_COLOR
            border_color = NEON_GREEN
        else:
            # 普通状态：渐变背景
            draw_gradient_rect(screen, BUTTON_BG_COLOR, (20, 50, 20), button_rect)
            text_color = MENU_NORMAL_COLOR
            border_color = BUTTON_BORDER_COLOR
        
        # 绘制按钮边框
        pygame.draw.rect(screen, border_color, button_rect, 2, border_radius=8)
        
        # 绘制按钮文字
        if action == "start":
            text = "开始游戏"
        elif action == "rules":
            text = "游戏规则"
        elif action == "exit":
            text = "退出游戏"
        
        text_surface = button_font.render(text, True, text_color)
        text_rect = text_surface.get_rect(center=button_rect.center)
        screen.blit(text_surface, text_rect)
    
    return menu_buttons

def handle_menu_click(pos, buttons):
    """处理菜单点击事件 - 供主游戏调用"""
    for action, button_rect in buttons:
        if button_rect.collidepoint(pos):
            return action
    return None

def draw_exit_confirm_dialog(screen, total_width, screen_height):
    """绘制退出确认对话框"""
    # 创建透明遮罩（完全透明）
    overlay = pygame.Surface((total_width, screen_height))
    overlay.set_alpha(0)  # 设置为完全透明
    overlay.fill((0, 0, 0))
    screen.blit(overlay, (0, 0))
    
    # 对话框尺寸和位置
    dialog_width = 400
    dialog_height = 200
    dialog_x = (total_width - dialog_width) // 2
    dialog_y = (screen_height - dialog_height) // 2
    
    # 绘制对话框背景
    dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
    draw_gradient_rect(screen, (40, 60, 40), (30, 50, 30), dialog_rect)
    pygame.draw.rect(screen, NEON_GREEN, dialog_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制标题
    title_text = title_font.render("确认退出", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 40))
    screen.blit(title_text, title_rect)
    
    # 绘制内容
    content_text = content_font.render("确定要退出游戏吗？", True, TEXT_COLOR)
    content_rect = content_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 80))
    screen.blit(content_text, content_rect)
    
    # 创建按钮
    button_width = 100
    button_height = 40
    button_spacing = 30
    
    # 是按钮
    yes_button = pygame.Rect(dialog_x + dialog_width // 2 - button_width - button_spacing // 2, 
                            dialog_y + dialog_height - 70, button_width, button_height)
    
    # 否按钮
    no_button = pygame.Rect(dialog_x + dialog_width // 2 + button_spacing // 2, 
                           dialog_y + dialog_height - 70, button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制是按钮
    is_yes_hover = yes_button.collidepoint(mouse_pos)
    if is_yes_hover:
        draw_glowing_rect(screen, (255, 80, 80), yes_button, glow_size=2)
        yes_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 40, 40), (60, 30, 30), yes_button)
        yes_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (255, 100, 100), yes_button, 2, border_radius=8)
    yes_text = button_font.render("是", True, yes_text_color)
    yes_text_rect = yes_text.get_rect(center=yes_button.center)
    screen.blit(yes_text, yes_text_rect)
    
    # 绘制否按钮
    is_no_hover = no_button.collidepoint(mouse_pos)
    if is_no_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, no_button, glow_size=2)
        no_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 50, 30), no_button)
        no_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, no_button, 2, border_radius=8)
    no_text = button_font.render("否", True, no_text_color)
    no_text_rect = no_text.get_rect(center=no_button.center)
    screen.blit(no_text, no_text_rect)
    
    return yes_button, no_button

def draw_rules_screen(screen, total_width, screen_height, scroll_offset=0):
    """绘制游戏规则界面"""
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 36, bold=True)
    subtitle_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制背景
    draw_gradient_rect(screen, BG_COLOR, (0, 20, 0), 
                       pygame.Rect(0, 0, total_width, screen_height))
    
    # 绘制标题
    title_text = title_font.render("游戏规则", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(total_width // 2, 60))
    screen.blit(title_text, title_rect)
    
    # 返回按钮
    back_button = pygame.Rect(30, 30, 80, 35)
    is_hover = back_button.collidepoint(pygame.mouse.get_pos())
    
    if is_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, back_button, glow_size=2)
        text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 50, 30), back_button)
        text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, back_button, 2, border_radius=6)
    back_text = button_font.render("返回", True, text_color)
    back_text_rect = back_text.get_rect(center=back_button.center)
    screen.blit(back_text, back_text_rect)
    
    # 扩大内容区域，减少边距
    content_area_x = 40
    content_area_y = 120
    content_area_width = total_width - 120
    content_area_height = screen_height - 160
    
    # 创建内容区域的裁剪表面
    content_surface = pygame.Surface((content_area_width, content_area_height))
    content_surface.fill(BG_COLOR)
    
    # 贪吃蛇游戏规则内容
    rules_content = [
        ("游戏目标", "控制蛇吃食物，让蛇变得越来越长，挑战更高的分数"),
        ("基础目标", "通过方向键控制蛇的移动，吃到食物让蛇变长"),
        ("进阶目标", "挑战更高的分数，体验不同的游戏主题"),
        ("终极目标", "获得更高的分数，创造个人最佳记录"),
        ("挑战目标", "尝试在有限空间内获得最高分数"),
        ("", ""),
        ("操作说明", "使用键盘控制蛇的移动方向"),
        ("↑", "向上移动蛇头"),
        ("↓", "向下移动蛇头"),
        ("←", "向左移动蛇头"),
        ("→", "向右移动蛇头"),
        ("空格", "开始/暂停游戏"),
        ("ESC", "打开游戏菜单"),
        ("+/-", "调整游戏速度"),
        ("A", "切换平滑动画"),
        ("1-4", "切换游戏主题"),
        ("", ""),
        ("计分规则", "根据吃到的食物类型计算分数"),
        ("普通食物", "1分，红色食物，让蛇变长1格"),
        ("特殊食物", "2分，金色食物，让蛇变长2格"),
        ("超级食物", "3分，紫色食物，让蛇变长3格"),
        ("双倍分数", "道具效果期间，所有得分翻倍"),
        ("障碍物惩罚", "撞击障碍物会扣分并缩短蛇身"),
        ("", ""),
        ("食物与道具", "游戏中会出现各种食物和道具"),
        ("普通食物", "红色圆形，基础食物，永久存在"),
        ("特殊食物", "金色圆形，高分食物，存在10秒"),
        ("超级食物", "紫色圆形，最高分食物，存在7秒"),
        ("加速道具", "橙色方块，提升移动速度10秒"),
        ("减速道具", "青色方块，降低移动速度10秒"),
        ("双倍分数", "金色方块，得分翻倍15秒"),
        ("清除障碍", "紫色方块，清除所有障碍物"),
        ("", ""),
        ("游戏特色", "贪吃蛇增强版包含多种特色功能"),
        ("不会死亡", "蛇撞墙或撞到自己不会死亡，可以继续游戏"),
        ("多种主题", "经典、深海、森林、霓虹四种主题可选"),
        ("特殊道具", "加速、减速、双倍分数等道具增加游戏趣味性"),
        ("障碍物系统", "蓝色障碍物增加游戏挑战性，撞击会扣分"),
        ("平滑移动", "蛇的移动更加平滑自然，可开关"),
        ("穿墙功能", "蛇可以穿过地图边界"),
        ("", ""),
        ("游戏技巧", "掌握这些技巧，提升你的游戏水平"),
        ("1", "优先吃特殊食物和超级食物，获得更高分数"),
        ("2", "合理使用道具，在适当时机使用加速或减速"),
        ("3", "注意障碍物位置，避免被困住"),
        ("4", "保持蛇的移动流畅，避免频繁改变方向"),
        ("5", "尝试不同的主题，找到最适合的视觉效果"),
        ("6", "练习快速反应，提高操作熟练度"),
        ("7", "保持冷静，不要被高速吓倒"),
        ("8", "多练习，熟能生巧"),
        ("", ""),
        ("界面说明", "游戏界面各区域功能"),
        ("左侧区域", "游戏主区域，显示蛇、食物、障碍物和道具"),
        ("右侧面板", "显示游戏状态信息，包括分数、时间、速度等"),
        ("分数显示", "实时显示当前得分"),
        ("存活时间", "显示游戏进行的时间"),
        ("当前速度", "显示蛇的移动速度，受道具影响会变色"),
        ("障碍物数量", "显示当前地图上的障碍物数量"),
        ("活动效果", "显示当前激活的道具效果及剩余时间"),
        ("主题显示", "显示当前使用的游戏主题")
    ]
    
    def render_wrapped_text(surface, text, font, color, rect, line_spacing=5):
        """渲染自动换行的文本"""
        words = text.split()
        lines = []
        current_line = []
        
        for word in words:
            test_line = ' '.join(current_line + [word])
            test_surface = font.render(test_line, True, color)
            test_width = test_surface.get_width()
            
            if test_width <= rect.width:
                current_line.append(word)
            else:
                if current_line:
                    lines.append(' '.join(current_line))
                    current_line = [word]
                else:
                    lines.append(word)
        
        if current_line:
            lines.append(' '.join(current_line))
        
        y = rect.y
        for line in lines:
            if y + font.get_height() <= rect.bottom:
                text_surface = font.render(line, True, color)
                surface.blit(text_surface, (rect.x, y))
                y += font.get_height() + line_spacing
        
        return len(lines) * (font.get_height() + line_spacing) - line_spacing
    
    # 计算内容总高度
    content_height = 0
    for title, content in rules_content:
        if title == "" and content == "":
            content_height += 20
        elif title in ["游戏目标", "操作说明", "计分规则", "游戏特色", "游戏技巧"]:
            content_height += 35
        else:
            if content:
                full_text = f"{title}: {content}"
            else:
                full_text = title
            
            text_rect = pygame.Rect(0, 0, content_area_width - 40, 1000)
            estimated_height = render_wrapped_text(
                pygame.Surface((1, 1)), full_text, content_font, TEXT_COLOR, text_rect
            )
            content_height += max(25, estimated_height)
    
    # 绘制内容到内容表面
    y_pos = -scroll_offset
    for title, content in rules_content:
        if title == "" and content == "":
            y_pos += 20
            continue
        
        if y_pos + 25 > 0 and y_pos < content_area_height:
            if title in ["游戏目标", "操作说明", "计分规则", "游戏特色", "游戏技巧"]:
                text = subtitle_font.render(title, True, NEON_GREEN)
                content_surface.blit(text, (0, y_pos))
                y_pos += 35
            else:
                if content:
                    full_text = f"{title}: {content}"
                else:
                    full_text = title
                
                text_rect = pygame.Rect(20, y_pos, content_area_width - 40, content_area_height - y_pos)
                text_height = render_wrapped_text(content_surface, full_text, content_font, TEXT_COLOR, text_rect)
                y_pos += max(25, text_height)
        else:
            if title in ["游戏目标", "操作说明", "计分规则", "游戏特色", "游戏技巧"]:
                y_pos += 35
            else:
                if content:
                    full_text = f"{title}: {content}"
                else:
                    full_text = title
                
                text_rect = pygame.Rect(0, 0, content_area_width - 40, 1000)
                estimated_height = render_wrapped_text(
                    pygame.Surface((1, 1)), full_text, content_font, TEXT_COLOR, text_rect
                )
                y_pos += max(25, estimated_height)
    
    # 将内容表面绘制到主屏幕
    screen.blit(content_surface, (content_area_x, content_area_y))
    
    # 绘制滚动条（如果内容超出可视区域）
    if content_height > content_area_height:
        scrollbar_width = 12
        scrollbar_x = total_width - 40
        scrollbar_y = content_area_y
        
        scrollbar_bg = pygame.Rect(scrollbar_x, scrollbar_y, scrollbar_width, content_area_height)
        pygame.draw.rect(screen, (50, 70, 50), scrollbar_bg, border_radius=6)
        
        scroll_ratio = scroll_offset / max(1, content_height - content_area_height)
        slider_height = max(30, int(content_area_height * (content_area_height / content_height)))
        slider_y = scrollbar_y + int(scroll_ratio * (content_area_height - slider_height))
        
        slider_rect = pygame.Rect(scrollbar_x, slider_y, scrollbar_width, slider_height)
        pygame.draw.rect(screen, NEON_GREEN, slider_rect, border_radius=6)
        
        pygame.draw.rect(screen, BUTTON_BORDER_COLOR, scrollbar_bg, 1, border_radius=6)
    
    return back_button, content_height, content_area_height

# 以下是独立运行时的代码，主游戏不会使用
if __name__ == "__main__":
    # 初始化pygame
    pygame.init()
    
    # 创建窗口
    screen = pygame.display.set_mode((TOTAL_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("贪吃蛇 - 主菜单")
    
    # 显示初始化菜单
    menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
    
    running = True
    showing_rules = False
    showing_exit_confirm = False
    scroll_offset = 0
    content_height = 0
    content_area_height = 0
    dragging_scrollbar = False
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if showing_exit_confirm:
                        yes_button, no_button = draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                        if yes_button.collidepoint(event.pos):
                            running = False
                        elif no_button.collidepoint(event.pos):
                            showing_exit_confirm = False
                            menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                    elif showing_rules:
                        back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                        if back_button.collidepoint(event.pos):
                            showing_rules = False
                            scroll_offset = 0
                            menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                        else:
                            scrollbar_width = 12
                            scrollbar_x = TOTAL_WIDTH - 40
                            scrollbar_y = 120
                            content_area_height = SCREEN_HEIGHT - 180
                            
                            if content_height > content_area_height:
                                scrollbar_rect = pygame.Rect(scrollbar_x, scrollbar_y, scrollbar_width, content_area_height)
                                if scrollbar_rect.collidepoint(event.pos):
                                    dragging_scrollbar = True
                                    scroll_ratio = (event.pos[1] - scrollbar_y) / content_area_height
                                    scroll_ratio = max(0, min(1, scroll_ratio))
                                    scroll_offset = int(scroll_ratio * max(0, content_height - content_area_height))
                                    back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                    else:
                        result = handle_menu_click(event.pos, menu_buttons)
                        if result == "start":
                            print("开始游戏")
                            running = False
                        elif result == "rules":
                            showing_rules = True
                            back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                        elif result == "exit":
                            showing_exit_confirm = True
                            draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    dragging_scrollbar = False
            elif event.type == pygame.MOUSEWHEEL and showing_rules:
                scroll_offset -= event.y * 30
                scroll_offset = max(0, min(scroll_offset, max(0, content_height - content_area_height)))
                back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
            elif event.type == pygame.MOUSEMOTION:
                if showing_rules and dragging_scrollbar:
                    scrollbar_width = 12
                    scrollbar_x = TOTAL_WIDTH - 40
                    scrollbar_y = 120
                    content_area_height = SCREEN_HEIGHT - 180
                    
                    if content_height > content_area_height:
                        mouse_y = event.pos[1]
                        scroll_ratio = (mouse_y - scrollbar_y) / content_area_height
                        scroll_ratio = max(0, min(1, scroll_ratio))
                        scroll_offset = int(scroll_ratio * max(0, content_height - content_area_height))
                        back_button, content_height, content_area_height = draw_rules_screen(screen, TOTAL_WIDTH, SCREEN_HEIGHT, scroll_offset)
                elif showing_exit_confirm:
                    draw_exit_confirm_dialog(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
                elif not showing_rules:
                    menu_buttons = draw_menu(screen, TOTAL_WIDTH, SCREEN_HEIGHT)
    
    pygame.quit()
    sys.exit()

def draw_game_menu(screen, total_width, screen_height):
    """绘制游戏内菜单弹窗"""
    # 创建半透明遮罩覆盖整个屏幕
    overlay = pygame.Surface((total_width, screen_height))
    overlay.set_alpha(128)  # 设置为半透明
    overlay.fill((0, 0, 0))
    screen.blit(overlay, (0, 0))
    
    # 菜单尺寸和位置
    menu_width = 320
    menu_height = 320
    menu_x = (total_width - menu_width) // 2
    menu_y = (screen_height - menu_height) // 2
    
    # 绘制菜单背景（半透明）
    menu_rect = pygame.Rect(menu_x, menu_y, menu_width, menu_height)
    # 创建半透明的菜单背景
    menu_surface = pygame.Surface((menu_width, menu_height))
    menu_surface.set_alpha(200)  # 设置透明度
    draw_gradient_rect(menu_surface, (40, 60, 40), (30, 50, 30), pygame.Rect(0, 0, menu_width, menu_height))
    screen.blit(menu_surface, (menu_x, menu_y))
    pygame.draw.rect(screen, NEON_GREEN, menu_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 32, bold=True)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24)
    
    # 绘制标题
    title_text = title_font.render("游戏菜单", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(menu_x + menu_width // 2, menu_y + 50))
    screen.blit(title_text, title_rect)
    
    # 创建按钮
    button_width = 220
    button_height = 50
    button_spacing = 25
    buttons_start_y = menu_y + 100
    
    # 继续游戏按钮
    continue_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                                 buttons_start_y, button_width, button_height)
    
    # 游戏说明按钮
    rules_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                              buttons_start_y + button_height + button_spacing, 
                              button_width, button_height)
    
    # 退出游戏按钮
    exit_button = pygame.Rect(menu_x + (menu_width - button_width) // 2, 
                             buttons_start_y + 2 * (button_height + button_spacing), 
                             button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制继续游戏按钮
    is_continue_hover = continue_button.collidepoint(mouse_pos)
    if is_continue_hover:
        draw_glowing_rect(screen, (60, 120, 60), continue_button, glow_size=2)
        continue_text_color = WHITE
    else:
        draw_gradient_rect(screen, (40, 80, 40), (30, 60, 30), continue_button)
        continue_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (80, 160, 80), continue_button, 2, border_radius=8)
    continue_text = button_font.render("继续游戏", True, continue_text_color)
    continue_text_rect = continue_text.get_rect(center=continue_button.center)
    screen.blit(continue_text, continue_text_rect)
    
    # 绘制游戏说明按钮
    is_rules_hover = rules_button.collidepoint(mouse_pos)
    if is_rules_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, rules_button, glow_size=2)
        rules_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 50, 30), rules_button)
        rules_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, rules_button, 2, border_radius=8)
    rules_text = button_font.render("游戏说明", True, rules_text_color)
    rules_text_rect = rules_text.get_rect(center=rules_button.center)
    screen.blit(rules_text, rules_text_rect)
    
    # 绘制退出游戏按钮
    is_exit_hover = exit_button.collidepoint(mouse_pos)
    if is_exit_hover:
        draw_glowing_rect(screen, (120, 40, 40), exit_button, glow_size=2)
        exit_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 30, 30), (60, 20, 20), exit_button)
        exit_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (160, 60, 60), exit_button, 2, border_radius=8)
    exit_text = button_font.render("退出游戏", True, exit_text_color)
    exit_text_rect = exit_text.get_rect(center=exit_button.center)
    screen.blit(exit_text, exit_text_rect)
    
    return continue_button, rules_button, exit_button

def draw_game_exit_confirm_dialog(screen, total_width, screen_height):
    """绘制游戏内退出确认对话框"""
    # 创建半透明遮罩
    overlay = pygame.Surface((total_width, screen_height))
    overlay.set_alpha(128)  # 设置为半透明
    overlay.fill((0, 0, 0))
    screen.blit(overlay, (0, 0))
    
    # 对话框尺寸和位置
    dialog_width = 400
    dialog_height = 200
    dialog_x = (total_width - dialog_width) // 2
    dialog_y = (screen_height - dialog_height) // 2
    
    # 绘制对话框背景
    dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
    draw_gradient_rect(screen, (40, 60, 40), (30, 50, 30), dialog_rect)
    pygame.draw.rect(screen, NEON_GREEN, dialog_rect, 3, border_radius=12)
    
    # 加载字体
    title_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 24, bold=True)
    content_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 18)
    button_font = pygame.font.SysFont("SimSun, Microsoft YaHei", 20)
    
    # 绘制标题
    title_text = title_font.render("确认退出", True, MENU_HIGHLIGHT_COLOR)
    title_rect = title_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 40))
    screen.blit(title_text, title_rect)
    
    # 绘制内容
    content_text = content_font.render("确定要退出到主菜单吗？", True, TEXT_COLOR)
    content_rect = content_text.get_rect(center=(dialog_x + dialog_width // 2, dialog_y + 80))
    screen.blit(content_text, content_rect)
    
    # 创建按钮
    button_width = 100
    button_height = 40
    button_spacing = 30
    
    # 是按钮
    yes_button = pygame.Rect(dialog_x + dialog_width // 2 - button_width - button_spacing // 2, 
                            dialog_y + dialog_height - 70, button_width, button_height)
    
    # 否按钮
    no_button = pygame.Rect(dialog_x + dialog_width // 2 + button_spacing // 2, 
                           dialog_y + dialog_height - 70, button_width, button_height)
    
    # 获取鼠标位置
    mouse_pos = pygame.mouse.get_pos()
    
    # 绘制是按钮
    is_yes_hover = yes_button.collidepoint(mouse_pos)
    if is_yes_hover:
        draw_glowing_rect(screen, (255, 80, 80), yes_button, glow_size=2)
        yes_text_color = WHITE
    else:
        draw_gradient_rect(screen, (80, 40, 40), (60, 30, 30), yes_button)
        yes_text_color = (200, 200, 200)
    
    pygame.draw.rect(screen, (255, 100, 100), yes_button, 2, border_radius=8)
    yes_text = button_font.render("退出", True, yes_text_color)
    yes_text_rect = yes_text.get_rect(center=yes_button.center)
    screen.blit(yes_text, yes_text_rect)
    
    # 绘制否按钮
    is_no_hover = no_button.collidepoint(mouse_pos)
    if is_no_hover:
        draw_glowing_rect(screen, BUTTON_HOVER_COLOR, no_button, glow_size=2)
        no_text_color = MENU_HIGHLIGHT_COLOR
    else:
        draw_gradient_rect(screen, BUTTON_BG_COLOR, (30, 50, 30), no_button)
        no_text_color = MENU_NORMAL_COLOR
    
    pygame.draw.rect(screen, BUTTON_BORDER_COLOR, no_button, 2, border_radius=8)
    no_text = button_font.render("取消", True, no_text_color)
    no_text_rect = no_text.get_rect(center=no_button.center)
    screen.blit(no_text, no_text_rect)
    
    return yes_button, no_button
